package com.fuang.dynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by Fuang on 2017-9-23.
 */
public class DynamicProxyTest{
    interface IHello{
        void sayHello( ) ;
    }

    static class Hello implements IHello {
        @Override
        public void sayHello() {
            System.out.println(" hello world");
        }

        public void sayBye() {
            System.out.println("Bye Bye");
        }
    }

    static class DynamicProxy implements InvocationHandler {
        Object originalObj;

        Object bind(Object originalObj) {
            this.originalObj = originalObj;
            return Proxy.newProxyInstance(originalObj.getClass().getClassLoader(), originalObj.getClass().getInterfaces(), this); // 生成代理类
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println(" welcome");
            return method.invoke(originalObj, args);
        }
    }

    public static void main(String[] args) {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", " true");
        Hello nativeHello = new Hello();
        IHello hello = (IHello) new DynamicProxy().bind(nativeHello); // 只能代理接口中的方法
        hello.sayHello();
        nativeHello.sayHello();
    }
}
